package com.zhouheng.springbootmultithreading.tuling.jmm.success;

import com.zhouheng.springbootmultithreading.tuling.factory.UnsafeFactory;

/**
 * 通过主动调用内存屏障解决
 *
 * UnsafeFactory.getUnsafe().storeFence();
 *
 * storeFence也会调用lock 前缀指令
 */
public class VisibilitySuccessTest2 {

    private boolean flag = true;
    private int count = 0;

    public void refresh() {
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag:" + flag);
    }

    public void load() {
        System.out.println(Thread.currentThread().getName() + "开始执行.....");
        while (flag) {
            //TODO  业务逻辑
            count++;
            // 主动调用内存屏障
            UnsafeFactory.getUnsafe().storeFence();
        }
        System.out.println(Thread.currentThread().getName() + "跳出循环: count=" + count);
    }

    public static void main(String[] args) throws InterruptedException {
        VisibilitySuccessTest2 test = new VisibilitySuccessTest2();

        // 线程threadA模拟数据加载场景
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        // 让threadA执行一会儿
        Thread.sleep(1000);
        // 线程threadB通过flag控制threadA的执行时间
        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();
    }

}
